/**
 * 替换打包后的资源
 * 可去除代码中的mark或进行html、static等文件的内容替换
 */
class ClearMarkPlugin {
  constructor(options) {
    this.options = options;
  }

  apply(compiler){
    const { match, target, rules } = this.options;
    compiler.plugin('emit', (compilation, callback) => {
      console.log('[CMP]Replace match: ' + match);
      Object.keys(compilation.assets).map(fileName => {
        if(new RegExp(target).test(fileName)){
          let fileContent = compilation.assets[fileName].source().replace(match, rules);
          compilation.assets[fileName] = {
            source: () => {
              return fileContent;
            },
            size: () => {
              return fileContent.length;
            }
          };
          console.log('[CMP]' + fileName + ' has been replaced!')
        }
      });
      callback();
    })
  }
}

module.exports = ClearMarkPlugin;
